'use client'

import React, { useState, useMemo, useCallback, memo } from 'react'
import { Card, Table, Button, Input, Select, Form, Modal, Space, message, Popconfirm } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'

interface Menu {
  id: number
  name: string
  path: string
  icon: string
  parentId: number | null
  sort: number
  status: string
  createTime: string
}

// 使用 memo 优化组件，避免不必要的重渲染
const MenusPage = memo(function MenusPage() {
  const [menus, setMenus] = useState<Menu[]>([
    { id: 1, name: '仪表盘', path: '/', icon: 'DashboardOutlined', parentId: null, sort: 1, status: '启用', createTime: '2024-01-15 10:00:00' },
    { id: 2, name: '用户管理', path: '/users', icon: 'UserOutlined', parentId: null, sort: 2, status: '启用', createTime: '2024-01-15 10:00:00' },
    { id: 3, name: '部门管理', path: '/departments', icon: 'TeamOutlined', parentId: null, sort: 3, status: '启用', createTime: '2024-01-15 10:00:00' },
    { id: 4, name: '菜单管理', path: '/menus', icon: 'MenuOutlined', parentId: null, sort: 4, status: '启用', createTime: '2024-01-15 10:00:00' },
    { id: 5, name: '用户列表', path: '/users/list', icon: 'UserOutlined', parentId: 2, sort: 1, status: '启用', createTime: '2024-01-15 10:00:00' },
    { id: 6, name: '用户详情', path: '/users/detail', icon: 'UserOutlined', parentId: 2, sort: 2, status: '禁用', createTime: '2024-01-15 10:00:00' },
  ])
  const [filteredMenus, setFilteredMenus] = useState<Menu[]>(menus)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editingMenu, setEditingMenu] = useState<Menu | null>(null)
  const [searchForm] = Form.useForm()
  const [form] = Form.useForm()

  // 使用 useMemo 优化选项数据
  const statusOptions = useMemo(() => ['启用', '禁用'], [])

  // 使用 useMemo 优化列定义
  const columns = useMemo(() => [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
    { title: '菜单名称', dataIndex: 'name', key: 'name' },
    { title: '路径', dataIndex: 'path', key: 'path' },
    { title: '图标', dataIndex: 'icon', key: 'icon' },
    { 
      title: '父级菜单', 
      dataIndex: 'parentId', 
      key: 'parentId',
      render: (parentId: number | null) => {
        if (!parentId) return '顶级菜单'
        const parent = menus.find(m => m.id === parentId)
        return parent ? parent.name : '-'
      }
    },
    { title: '排序', dataIndex: 'sort', key: 'sort' },
    { title: '状态', dataIndex: 'status', key: 'status' },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: any, record: Menu) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除这个菜单吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ], [menus])

  // 查询栏筛选逻辑 - 使用 useCallback 优化
  const handleSearch = useCallback((values: any) => {
    let data = [...menus]
    if (values.name) {
      data = data.filter(m => m.name.includes(values.name))
    }
    if (values.status) {
      data = data.filter(m => m.status === values.status)
    }
    setFilteredMenus(data)
  }, [menus])

  const handleReset = useCallback(() => {
    searchForm.resetFields()
    setFilteredMenus(menus)
  }, [searchForm, menus])

  const handleAdd = useCallback(() => {
    setEditingMenu(null)
    form.resetFields()
    setIsModalVisible(true)
  }, [form])

  const handleEdit = useCallback((menu: Menu) => {
    setEditingMenu(menu)
    form.setFieldsValue(menu)
    setIsModalVisible(true)
  }, [form])

  const handleDelete = useCallback((id: number) => {
    // 删除菜单及其子菜单
    const deleteIds = new Set([id])
    const findChildren = (parentId: number) => {
      menus.forEach(menu => {
        if (menu.parentId === parentId) {
          deleteIds.add(menu.id)
          findChildren(menu.id)
        }
      })
    }
    findChildren(id)
    setMenus(menus.filter(menu => !deleteIds.has(menu.id)))
    setFilteredMenus(filteredMenus.filter(menu => !deleteIds.has(menu.id)))
    message.success('删除成功')
  }, [menus, filteredMenus])

  const handleModalOk = useCallback(() => {
    form.validateFields().then((values: any) => {
      if (editingMenu) {
        setMenus(menus.map(menu =>
          menu.id === editingMenu.id ? { ...menu, ...values } : menu
        ))
        setFilteredMenus(filteredMenus.map(menu =>
          menu.id === editingMenu.id ? { ...menu, ...values } : menu
        ))
        message.success('更新成功')
      } else {
        const newMenu: Menu = {
          id: Math.max(...menus.map(m => m.id)) + 1,
          ...values,
          createTime: new Date().toLocaleString()
        }
        setMenus([...menus, newMenu])
        setFilteredMenus([...filteredMenus, newMenu])
        message.success('创建成功')
      }
      setIsModalVisible(false)
      form.resetFields()
    })
  }, [editingMenu, menus, filteredMenus, form])

  return (
    <div style={{ padding: 16, height: '100%', minHeight: 0, display: 'flex', flexDirection: 'column' }}>
      {/* 查询条件卡片 */}
      <Card style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
        >
          <Form.Item name="name" label="菜单名称">
            <Input placeholder="请输入菜单名称" allowClear style={{ width: 160 }} />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="全部" allowClear style={{ width: 120 }}>
              {statusOptions.map(st => (
                <Select.Option key={st} value={st}>{st}</Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">查询</Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={handleReset}>重置</Button>
          </Form.Item>
        </Form>
      </Card>

      {/* 表格内容卡片 */}
      <Card 
        style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }} 
        styles={{ body: { padding: '12px 24px', flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' } }}
      >
        <div style={{ marginTop: 0, marginBottom: 8, display: 'flex', justifyContent: 'flex-end' }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增菜单
          </Button>
        </div>
        <Table
          columns={columns}
          dataSource={filteredMenus}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
        />
      </Card>

      <Modal
        title={editingMenu ? '编辑菜单' : '新增菜单'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="菜单名称"
            rules={[{ required: true, message: '请输入菜单名称' }]}
          >
            <Input placeholder="请输入菜单名称" />
          </Form.Item>
          <Form.Item
            name="path"
            label="路径"
            rules={[{ required: true, message: '请输入路径' }]}
          >
            <Input placeholder="请输入路径，如：/users" />
          </Form.Item>
          <Form.Item
            name="icon"
            label="图标"
            rules={[{ required: true, message: '请输入图标名称' }]}
          >
            <Input placeholder="请输入图标名称，如：UserOutlined" />
          </Form.Item>
          <Form.Item
            name="parentId"
            label="父级菜单"
          >
            <Select placeholder="请选择父级菜单" allowClear>
              <Select.Option value={null}>顶级菜单</Select.Option>
              {menus.map(menu => (
                <Select.Option key={menu.id} value={menu.id}>
                  {menu.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="sort"
            label="排序"
            rules={[{ required: true, message: '请输入排序' }]}
          >
            <Input type="number" placeholder="请输入排序数字" />
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Select.Option value="启用">启用</Select.Option>
              <Select.Option value="禁用">禁用</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
})

export default MenusPage 